package com.zhongge.dao;

import com.zhongge.entity.User;
import com.zhongge.util.DbUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UserDao
 * @Description TODO
 * @Author zhongge
 * @Version 1.0
 */
public class UserDao {
    // 添加用户
    public boolean addUser(User user) {
        Connection connection = null;
        PreparedStatement pt = null;

        int count = -1;
        try {
            connection = DbUtils.getConnection();
            String sql = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";

            pt = connection.prepareStatement(sql);

            pt.setString(1, user.getUsername());
            pt.setString(2, user.getEmail());
            pt.setString(3, user.getPassword());

            count = pt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DbUtils.close(null, pt, connection);
        }

        if (count > 0) {
            return true;
        }
        return false;
    }

    //获取所有用户
    public List<User> getAllUsers() {
        List<User> userList = new ArrayList<>();


        Connection connection = null;
        PreparedStatement pt = null;
        ResultSet rs = null;
        try {

            connection = DbUtils.getConnection();
            String sql = "SELECT * FROM users";

            pt = connection.prepareStatement(sql);


            rs = pt.executeQuery();

            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setEmail(rs.getString("email"));
                user.setPassword(rs.getString("password"));

                userList.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return userList;
    }
}
